package com.leantech.android.browser.ui.search.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.view.postDelayed
import androidx.recyclerview.widget.RecyclerView
import com.cscj.android.repository.db.entity.SearchHistoryEntity
import com.leantech.android.browser.databinding.ItemSearchHistorySectionBinding
import com.leantech.android.browser.utils.onThrottleClick
import com.leantech.android.browser.utils.show
import com.leantech.android.browser.views.FlexBoxMaxLinesLayout
import okhttp3.internal.toImmutableList

class SearchHistorySectionAdapter(private val adapterCallback: SearchHistorySectionAdapterCallback) :
    RecyclerView.Adapter<SearchHistorySectionAdapter.SearchHistorySectionViewHolder>() {

    companion object {
        private const val PayloadUpdateEditMode = 2

        private const val MinLine = 2
        private const val MaxLine = 20
    }


    private val data = mutableListOf<SearchHistoryEntity>()

    private var editMode = false

    fun submitList(histories: List<SearchHistoryEntity>) {
        data.clear()
        data.addAll(histories)
        notifyDataSetChanged()
    }

    fun toggleEditMode(on: Boolean) {
        if (editMode == on) return
        editMode = on
        notifyItemChanged(0, PayloadUpdateEditMode)
    }

    fun isEditMode(): Boolean {
        return editMode
    }

    override fun onCreateViewHolder(
        parent: ViewGroup, viewType: Int
    ): SearchHistorySectionViewHolder {
        val binding = ItemSearchHistorySectionBinding.inflate(
            LayoutInflater.from(parent.context), parent, false
        )
        return SearchHistorySectionViewHolder(binding)
    }

    override fun onBindViewHolder(holder: SearchHistorySectionViewHolder, position: Int) {
        holder.bind(data.toImmutableList(), editMode, adapterCallback)
    }

    override fun onBindViewHolder(
        holder: SearchHistorySectionViewHolder, position: Int, payloads: MutableList<Any>
    ) {
        if (payloads.isEmpty()) {
            super.onBindViewHolder(holder, position, payloads)
        } else {
            payloads.forEach { payload ->
                when (payload) {
                    PayloadUpdateEditMode -> {
                        holder.updateEditMode(editMode, data.toImmutableList())
                    }

                    else -> {
                        super.onBindViewHolder(holder, position, payloads)
                    }
                }

            }
        }

    }

    override fun getItemCount(): Int {
        return if (data.isEmpty()) 0 else 1
    }

    interface SearchHistorySectionAdapterCallback : SearchHistoryAdapter.SearchHistoryItemCallback {

        fun onAllHistoryRemoved()

        fun onEnterEditMode()

        fun onCompleteClick()

    }

    class SearchHistorySectionViewHolder(private val binding: ItemSearchHistorySectionBinding) :
        RecyclerView.ViewHolder(binding.root) {

        fun bind(
            histories: List<SearchHistoryEntity>,
            editMode: Boolean,
            adapterCallback: SearchHistorySectionAdapterCallback
        ) {
            if (histories.isEmpty()) return
            val adapter = binding.recyclerView.adapter
            if (adapter == null) {
                binding.recyclerView.adapter = SearchHistoryAdapter(adapterCallback)
                val layoutManager = FlexBoxMaxLinesLayout(itemView.context).apply {
                    this.maxLine = MinLine
                }
                binding.recyclerView.layoutManager = layoutManager
            }

            updateEditMode(editMode, histories)
            submitList(histories)

            binding.ivDelete.onThrottleClick {
                adapterCallback.onEnterEditMode()
            }

            binding.btnDeleteAll.onThrottleClick {
                adapterCallback.onAllHistoryRemoved()
            }

            binding.btnToggle.onThrottleClick {
                toggleMaxVisibleLine(histories)
            }
        }


        private fun toggleMaxVisibleLine(histories: List<SearchHistoryEntity>) {
            val layoutManager =
                binding.recyclerView.layoutManager as? FlexBoxMaxLinesLayout ?: return
            val currentMaxVisibleLine = layoutManager.maxVisibleLines

            if (currentMaxVisibleLine == MinLine) {
                layoutManager.maxLine = MaxLine
            } else {
                layoutManager.maxLine = MinLine
            }

            val dataCount = histories.size
            binding.recyclerView.post {
                val maxLine = layoutManager.maxVisibleLines
                if (maxLine == MaxLine) {
                    val lineCount = layoutManager.flexLinesInternal.size
                    binding.btnToggle.show(lineCount >= 2)
                } else {
                    val visibleItemCount = layoutManager.getVisibleItemCount()
                    binding.btnToggle.show(visibleItemCount < dataCount)
                }
                binding.btnToggle.isSelected = maxLine == MaxLine
            }
        }

        fun submitList(histories: List<SearchHistoryEntity>) {
            val adapter = binding.recyclerView.adapter as? SearchHistoryAdapter ?: return
            adapter.submitList(histories)
            autoUpdateMaxLine(histories)
        }

        private fun autoUpdateMaxLine(histories: List<SearchHistoryEntity>) {
            binding.recyclerView.postDelayed(200) {
                val layoutManager = binding.recyclerView.layoutManager as? FlexBoxMaxLinesLayout
                    ?: return@postDelayed

                val maxLine = layoutManager.maxVisibleLines
                //determine max line
                if (maxLine == MinLine) {//2行的时候
                    val dataCount = histories.size
                    val flexItemCount = layoutManager.getVisibleItemCount()
                    binding.btnToggle.show(flexItemCount < dataCount)
                    binding.btnToggle.isSelected = false
                } else { //5行的时候
                    val lineCount = layoutManager.flexLinesInternal.size
                    if (lineCount <= MinLine) {//实际行数<=2行
                        layoutManager.maxLine = MinLine
                        binding.btnToggle.show(false)
                        binding.btnToggle.isSelected = false
                    } else {
                        binding.btnToggle.show(true)
                        binding.btnToggle.isSelected = true
                    }
                }

            }
        }

        fun updateEditMode(editMode: Boolean, histories: List<SearchHistoryEntity>) {
            val adapter = binding.recyclerView.adapter as? SearchHistoryAdapter ?: return
            adapter.show(editMode)
            binding.btnDeleteAll.show(editMode)
            binding.ivDelete.show(!editMode)

            autoUpdateMaxLine(histories)
        }

    }


}